var express = require('express');
var path = require('path');
var router = express.Router();
const fs = require('fs');
const busboy = require('busboy');
const { setAccountHasPortrait } = require('../model/account');
const message = require('../model/returnMessage');
const auth = require('../middleware/auth');

// router.get('/', (req, res) => {
//   res.send(
//     `<!DOCTYPE html>
//       <html>
//       <body>
//         <form action="home/upload" method="post" enctype="multipart/form-data">
//           <h1>选择上传的文件</h1>
//           <input type="file" name="file">
//           <input type="submit" value="上传">
//         </form>
//       </body>
//       </html>`
//   );
// });

router.post(
  '/upload',
  auth,
  (req, res, next) => {
    const bb = busboy({ headers: req.headers });
    bb.on('file', (name, file, info) => {
      if (!/^image\/(png)|(jpeg)$/.test(info.mimeType)) {
        res.status(401).send(message({}, '.png/.jpg/.jpeg picture needed.'));
        return;
      }
      try {
        file.pipe(
          fs.createWriteStream(
            path.join('./public/portrait', req.body.username + '.png')
          )
        );
      } catch (e) {
        res.status(500).send(message({}, 'Internal server error.'));
      }
    });

    bb.on('close', () => {
      next();
    });

    req.pipe(bb);
    return;
  },
  (req, res) => {
    setAccountHasPortrait(req.body.username, req.body.username + '.png').then(
      (r) => {
        res
          .status(200)
          .send(message({ username: req.body.username }, 'Portrait created.'));
      },
      (e) => {
        res.status(500).send(message({}, 'Internal server error'));
      }
    );
  }
);

module.exports = router;
